package com.contest.controller;

import com.contest.dto.request.CreateUserRequest;
import com.contest.dto.request.UpdateUserRequest;
import com.contest.dto.response.PagedResponse;
import com.contest.dto.response.UserDto;
import com.contest.entity.UserRole;
import com.contest.service.UserService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/admin/users")
@CrossOrigin(origins = "*", maxAge = 3600)
@PreAuthorize("hasRole('ADMIN')")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有用户（分页和过滤）
     */
    @GetMapping
    public ResponseEntity<PagedResponse<UserDto>> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) UserRole role,
            @RequestParam(required = false) Boolean enabled) {
        
        logger.info("管理员获取用户列表 - 页码: {}, 大小: {}, 排序: {} {}, 关键词: {}, 角色: {}, 启用状态: {}", 
                   page, size, sortBy, sortDir, keyword, role, enabled);
        
        PagedResponse<UserDto> users = userService.getAllUsers(page, size, sortBy, sortDir, keyword, role, enabled);
        return ResponseEntity.ok(users);
    }
    
    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{userId}")
    public ResponseEntity<UserDto> getUserById(@PathVariable Long userId) {
        logger.info("管理员获取用户详情: {}", userId);
        
        UserDto user = userService.getUserById(userId);
        return ResponseEntity.ok(user);
    }
    
    /**
     * 创建新用户
     */
    @PostMapping
    public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserRequest request) {
        logger.info("管理员创建用户: {}", request.getUsername());
        
        UserDto createdUser = userService.createUser(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<UserDto> updateUser(@PathVariable Long userId, 
                                            @Valid @RequestBody UpdateUserRequest request) {
        logger.info("管理员更新用户: {}", userId);
        
        UserDto updatedUser = userService.updateUser(userId, request);
        return ResponseEntity.ok(updatedUser);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long userId) {
        logger.info("管理员删除用户: {}", userId);
        
        userService.deleteUser(userId);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 启用用户
     */
    @PutMapping("/{userId}/enable")
    public ResponseEntity<UserDto> enableUser(@PathVariable Long userId) {
        logger.info("管理员启用用户: {}", userId);
        
        UserDto enabledUser = userService.enableUser(userId);
        return ResponseEntity.ok(enabledUser);
    }
    
    /**
     * 禁用用户
     */
    @PutMapping("/{userId}/disable")
    public ResponseEntity<UserDto> disableUser(@PathVariable Long userId) {
        logger.info("管理员禁用用户: {}", userId);
        
        UserDto disabledUser = userService.disableUser(userId);
        return ResponseEntity.ok(disabledUser);
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<UserService.UserStatsDto> getUserStats() {
        logger.info("管理员获取用户统计信息");
        
        UserService.UserStatsDto stats = userService.getUserStats();
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 批量启用用户
     */
    @PutMapping("/batch/enable")
    public ResponseEntity<String> enableUsers(@RequestBody Long[] userIds) {
        logger.info("管理员批量启用用户: {}", (Object) userIds);
        
        for (Long userId : userIds) {
            userService.enableUser(userId);
        }
        
        return ResponseEntity.ok("批量启用用户成功");
    }
    
    /**
     * 批量禁用用户
     */
    @PutMapping("/batch/disable")
    public ResponseEntity<String> disableUsers(@RequestBody Long[] userIds) {
        logger.info("管理员批量禁用用户: {}", (Object) userIds);
        
        for (Long userId : userIds) {
            userService.disableUser(userId);
        }
        
        return ResponseEntity.ok("批量禁用用户成功");
    }
}